package com.himore.api.web.core.config;

import com.alibaba.fastjson.JSONObject;
import com.himore.api.common.core.domain.AjaxResult;
import com.himore.api.common.core.domain.entity.SysUser;
import com.himore.api.common.utils.SecurityUtils;
import com.himore.api.common.utils.ServletUtils;
import com.himore.api.common.utils.StringUtils;
import com.himore.api.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 拦截请求，在访问controller调用之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String  token = request.getHeader("Authorization");
        System.out.println(token);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        SysUser currentUser = sysUserService.selectUserById(sysUser.getUserId());
        if(StringUtils.isNull(currentUser)){
            AjaxResult ajaxResult = AjaxResult.error(401,"验证失败，请重新登录！");
            ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
            return false;
        }else{
            return true;
        }

        /**
         * false:请求被拦截，被驳回，验证出现问题
         * true: 请求在经过验证效验以后，是OK的,是可以放行
         */

    }

    /**
     * 请求访问controller之后，渲染视图之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求访问controller之后，渲染视图之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}